package com.sihan.framework.etm.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SpaceCoordinatesUtil {

    public final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    private static final Logger LOG = LoggerFactory.getLogger(SpaceCoordinatesUtil.class);
    static double pi = 3.14159265358979324;
    static double a = 6378245.0;
    static double ee = 0.00669342162296594323;

    /**
     * 判断单组空间坐标格式是否正确
     *
     * @param zb
     * @return
     */
    public static boolean validateSpaceCoordinates(String zb) {
        if (zb == null || zb.equals("")) {
            return true;
        }
        String[] array = zb.split(",");
        if (array.length != 2) {
            return false;
        }
        for (int i = 0; i < 2; i++) {
            if (!isNumber(array[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断多组空间坐标格式是否正确
     *
     * @param zb
     * @return
     */
    public static boolean validateSpaceCoordinatesGroup(String zbs) {
        if (zbs == null || zbs.equals("")) {
            return true;
        }
        String[] array = zbs.split(";");
        for (int i = 0; i < array.length; i++) {
            if (!validateSpaceCoordinates2(array[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断多组空间坐标中的一组格式是否正确
     *
     * @param zb
     * @return
     */
    public static boolean validateSpaceCoordinates2(String zb) {
        if (zb == null || zb.equals("")) {
            return false;
        }
        String[] array = zb.split(",");
        if (array.length != 2) {
            return false;
        }
        for (int i = 0; i < 2; i++) {
            if (!isNumber(array[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断字符串是否是数字
     *
     * @param zb
     * @return
     */
    private static boolean isNumber(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
        String reg = "\\d+(\\.\\d+)?";
        return str.matches(reg);
    }

    public static String connectURL(String dest_url, String commString) {
        String rec_string = "";
        URL url = null;
        HttpURLConnection urlconn = null;
        OutputStream out = null;
        BufferedReader rd = null;
        try {
            url = new URL(dest_url);
            urlconn = (HttpURLConnection) url.openConnection();
            urlconn.setReadTimeout(1000 * 30);
            urlconn.setRequestMethod("POST");
            urlconn.setDoInput(true);
            urlconn.setDoOutput(true);
            out = urlconn.getOutputStream();
            out.write(commString.getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
            rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            int ch;
            while ((ch = rd.read()) > -1)
                sb.append((char) ch);
            rec_string = sb.toString();
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return "";
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (urlconn != null) {
                    urlconn.disconnect();
                }
                if (rd != null) {
                    rd.close();
                }
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
        }
        return rec_string;
    }

//	/**
//	 * 坐标系转换
//	 * @param zb
//	 * @return
//	 */
//	public static String changeSpaceCoordinates(String zb) {
//		String result = "";
//		String czb =connectURL("http://api.map.baidu.com/geoconv/v1/?coords="+zb+"&from=1&to=5&output=json&ak=r8TEKFE9ArGeiQ4X4015E3O65tVV5M6t","");
//		Map maps = (Map)JSON.parse(czb);  
//        for (Object map : maps.entrySet()){  
//            if(((Map.Entry)map).getKey().toString().equals("result")) {
//            	List<Map> mapsList1 = (List<Map>)JSONArray.parse(((Map.Entry)map).getValue().toString());
//            	for(Map maps1 : mapsList1) {
//                    for (Object map1 : maps1.entrySet()){  
//                        if(((Map.Entry)map1).getKey().toString().equals("x")) {
//                        	result = result + ((Map.Entry)map1).getValue().toString() + ",";
//                        }else if(((Map.Entry)map1).getKey().toString().equals("y")) {
//                        	result = result + ((Map.Entry)map1).getValue().toString() + ";";
//                        }
//                    }  
//            	}
//            }
//        }  
//        result = result.substring(0, result.length()-1);
//		return result;
//	}

    public static double[] wgs2bd(double lat, double lon) {
        double[] wgs2gcj = wgs2gcj(lat, lon);
        double[] gcj2bd = gcj2bd(wgs2gcj[0], wgs2gcj[1]);
        return gcj2bd;
    }

    public static double[] gcj2bd(double lat, double lon) {
        double x = lon, y = lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double bd_lon = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        return new double[]{bd_lat, bd_lon};
    }

    public static double[] bd2gcj(double lat, double lon) {
        double x = lon - 0.0065, y = lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        double gg_lon = z * Math.cos(theta);
        double gg_lat = z * Math.sin(theta);
        return new double[]{gg_lat, gg_lon};
    }

    public static double[] wgs2gcj(double lat, double lon) {
        double dLat = transformLat(lon - 105.0, lat - 35.0);
        double dLon = transformLon(lon - 105.0, lat - 35.0);
        double radLat = lat / 180.0 * pi;
        double magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        double sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
        double mgLat = lat + dLat;
        double mgLon = lon + dLon;
        double[] loc = {mgLat, mgLon};
        return loc;
    }

    private static double transformLat(double lat, double lon) {
        double ret = -100.0 + 2.0 * lat + 3.0 * lon + 0.2 * lon * lon + 0.1 * lat * lon + 0.2 * Math.sqrt(Math.abs(lat));
        ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lon * pi) + 40.0 * Math.sin(lon / 3.0 * pi)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lon / 12.0 * pi) + 320 * Math.sin(lon * pi / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    private static double transformLon(double lat, double lon) {
        double ret = 300.0 + lat + 2.0 * lon + 0.1 * lat * lat + 0.1 * lat * lon + 0.1 * Math.sqrt(Math.abs(lat));
        ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lat / 12.0 * pi) + 300.0 * Math.sin(lat / 30.0 * pi)) * 2.0 / 3.0;
        return ret;
    }

    /**
     * 坐标系转换
     *
     * @param zb
     * @return
     */
    public static String changeSpaceCoordinates(String zb) {
        String result = "";
        String[] zbStr = zb.split(",");
        String longitude = zbStr[0];
        String latitude = zbStr[1];
        double[] tt = SpaceCoordinatesUtil.wgs2bd(Double.parseDouble(latitude), Double.parseDouble(longitude));
        result = tt[1] + "," + tt[0];
        return result;
    }


    public static void main(String[] args) {

        String s = changeSpaceCoordinates("104.674565131833,30.0780469911666");
        System.out.println(s);
    }
}
